package com.zxl.controller;

import com.alibaba.fastjson.JSON;
import com.zxl.constants.Constants;
import com.zxl.feign.HomeFeign;
import com.zxl.vo.GoodsType;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.thymeleaf.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @packageName com.zxl.controller
 * @ClassName
 * @Author zxl
 * @Description //TODO
 * @date
 **/
@RequestMapping("/home")
@Controller
public class HomeController {

    @Autowired
    private HomeFeign homeFeign;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    @RequestMapping(value = {"/", "/index.html", "index"})
    public String list(Model model) {

        String s = redisTemplate.opsForValue().get(Constants.HOME_GOODS_TYPE_LIST_KEY);
        List<GoodsType> list;
        if (StringUtils.isEmpty(s)) {
            list = farmat();
        } else {
            list = JSON.parseObject(s, List.class);
        }
        model.addAttribute("glist", list);
        return "index";
    }


    private List farmat() {
        RLock lock = redissonClient.getLock(Constants.HOME_GOODS_TYPE_LOCK);
        lock.lock();
        try {
            String data = redisTemplate.opsForValue().get(Constants.HOME_GOODS_TYPE_LIST_KEY);
            if (StringUtils.isEmpty(data)) {
                List<GoodsType> list = homeFeign.list();
                List<GoodsType> par = new ArrayList<>();
                Map<Integer, GoodsType> map = new HashMap<>();
                for (GoodsType goodsType : list) {
                    if (goodsType.getPid() == -1) {
                        map.put(goodsType.getId(), goodsType);
                        par.add(goodsType);
                    }
                }
                for (GoodsType goodsType : list) {
                    if (map.containsKey(goodsType.getPid())) {
                        GoodsType goodsType1 = map.get(goodsType.getPid());
                        goodsType1.getChildren().add(goodsType);
                    }
                }
                String s = JSON.toJSONString(par);
                redisTemplate.opsForValue().set(Constants.HOME_GOODS_TYPE_LIST_KEY, s, 10, TimeUnit.DAYS);
                return par;
            }

        } finally {
            lock.unlock();
        }
        return null;
    }

}
